	package gui;

import gui.SimpleTable.MyTableCellRenderer;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;

	import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.*; 
import java.awt.event.*;  

import javax.swing.JList;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import controllers.LibrarianUIP;
import controllers.OBLSettings;

	import Entity.Book;
import Entity.BorrowRecored;

	import messagesPacks.ViewHistoryMessage;

	import java.awt.Color;
import java.awt.SystemColor;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 * This class representing a LibrarianViewHistory Gui
 * Date: 25/12/2012
 * @author Roman Faktorovich & Alon Shahaf
 *
 */

public class LibrarianViewHistory extends JPanel 
{

	
			private static final long serialVersionUID = 1L;
			private static WelcomeUI wui;
			private JLabel lblOblSubscriber;
			private JSeparator separator;
			private JButton btnBack;
			private SimpleTable historyTable ; 
			
			LibrarianUI subUI = null;
			private JList detailsList;
			
			/**lstActivityLogOBJ is for the subjects of book*/
			private DefaultListModel<String> lstActivityLogOBJ;
			private JList lstActivityLog;
			private JScrollPane scrollPane;
			
			ViewHistoryMessage answer;
			JButton btnExitButton;
		    JButton btnLogoutButton;
		
			private static Component curr_panel;
			JPopupMenu popup;
			JMenuItem popupTest1,popupTest2,popupTest3;
			public String man_ext_book_borrowed;
			
			private  LibrarianUIP luip=null;
			
//===============================================================================================
//			 Constructor
//			 
/**
*Constructor the LibrarianViewHistory with default values
*@param fatherPanel
*/		
		public LibrarianViewHistory(LibrarianUI fatherPanel)
		{
			super();
			this.luip=new LibrarianUIP();
			initialize();
		    this.subUI = fatherPanel;
		}

		/**
		 * This method initializes the panel
		 */
		private void initialize()
		{
			setLayout(null);
			this.setSize(OBLSettings.pane2Size[0],OBLSettings.pane2Size[1]);
			separator = new JSeparator();
			separator.setBounds(-17, 57, 855, 20);
			add(separator);
			
			lblOblSubscriber = new JLabel("OBL Librarian");
			lblOblSubscriber.setFont(new Font("Tahoma", Font.BOLD, 20));
			lblOblSubscriber.setBounds(317, 0, 165, 58);
			add(lblOblSubscriber);
			

			btnLogoutButton = new JButton("Logout");
			btnLogoutButton.setFont(new Font("Tahoma", Font.BOLD, 15));
			btnLogoutButton.setBounds(614, 11, 83, 41);
			add(btnLogoutButton);
			
			btnExitButton = new JButton("Exit");
			btnExitButton.setFont(new Font("Tahoma", Font.BOLD, 15));
			btnExitButton.setBounds(707, 11, 83, 41);
			add(btnExitButton);

			btnBack = new JButton("Back");
			btnBack.setFont(new Font("Tahoma", Font.BOLD, 15));
			btnBack.setBounds(26, 11, 83, 41);
			add(btnBack);
			
			String ColNames[] = { "Borrow Number","Book ISBN","CopyID", "Book Name","Borrow Date","Return Date","Actual Return Date"};
			historyTable = new SimpleTable(null, ColNames, 8, 60, 780, 360);
			historyTable.setColCenter(historyTable.table.getColumnCount());
		    add(historyTable.tblScrollPane,BorderLayout.CENTER);
		    
		    lstActivityLogOBJ = new DefaultListModel<String>();
			detailsList = new JList(lstActivityLogOBJ);
			detailsList.setOpaque(false);
			detailsList.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15));
			detailsList.setBackground(SystemColor.window);
			detailsList.setBorder(new LineBorder(SystemColor.controlShadow));
			detailsList.setBounds(8, 430, 780, 130);
			add(detailsList);
			curr_panel = this;
//=============================================================================================================		
//	                         Action Listeners
//=============================================================================================================			
			
			btnBack.addActionListener(new ActionListener() 
			{
				public void actionPerformed(ActionEvent e) 
				{
					historyTable.model.setRowCount(0);
					lstActivityLogOBJ.removeAllElements();
					

					  WelcomeUI.wui.switchPanel("OBL Librarian",subUI ,OBLSettings.pane2Size[0], OBLSettings.pane2Size[1]);

				}
			});
//==========================================================================================================		

			historyTable.table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
			{
				public void valueChanged(ListSelectionEvent e) 
				{
					JTable table = historyTable.table;

					if(table.getRowCount() > 0)	
					{	
						int row = table.getSelectedRow();

						if(row>=0)
						{ 
							lstActivityLogOBJ.removeAllElements();
							
				    		Object[] rowData = new Object[table.getColumnCount()];  
				    		for (int i = 0; i < table.getColumnCount(); i++) 
				    		{  
						         rowData[i] = table.getValueAt(row, i);  
				    		} 
				    		
			
				    		for(BorrowRecored var : answer.getBorrowList())
				    		{	 
				    			if(var.borrowNumber ==  Integer.parseInt( rowData[0].toString()))
				    			  {
				    				lstActivityLogOBJ.addElement("lateness days : " +calculateLatnessPiriod(var.returnDate ,var.actualReturnDate));
				    				lstActivityLogOBJ.addElement("book returned : " +var.bookReturned);
				    				man_ext_book_borrowed = var.bookReturned;
				    				lstActivityLogOBJ.addElement("book lost : " +var.bookLost);
				    				lstActivityLogOBJ.addElement("fines: " +String.valueOf(calculateFine(var.bookLost ,
				    				calculateLatnessPiriod(var.returnDate ,var.actualReturnDate)))+"\u20AA".toCharArray()[0]);
				    			  }

				    		 }//for
				    		
						}//if
					}//if
				}
				
			});
		
//================================================================================================================	
           //right click menu "lost book"
			//popup = new JPopupMenu();
            popupTest3=new JMenuItem("Lost Book");  
            popupTest3.addActionListener(new ActionListener()
            {
				@Override
				public void actionPerformed(ActionEvent arg0) 
				{
					// TODO Auto-generated method stub
					int row = historyTable.table.getSelectedRow();
					int bn = Integer.parseInt(historyTable.table.getValueAt(row, 0).toString());
					if (JOptionPane.showConfirmDialog(WelcomeUI.wui,"Are you sure?", "Quitting",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
					{
						int returnBookResult = luip.librarianReturnBook(null, 0);
						switch (returnBookResult)
						{
						
							case 2: // lost book update successfully
							{
								
								JOptionPane.showMessageDialog( WelcomeUI.wui, "Update Successfully!","Lost Book",JOptionPane.INFORMATION_MESSAGE);
								break;
							} 
							default: // Error
							{
								JOptionPane.showMessageDialog( WelcomeUI.wui, "Operation failed!","Warning",JOptionPane.ERROR_MESSAGE);				
								break;
							}
					  } // switch
					}
 
				}
			});  
			
//==================================================================================================================			
			//  right click menu on table "manual Extension"
//================================================================================================================	
            //right click menu "lost book"
			//popup = new JPopupMenu();
            popupTest3=new JMenuItem("Lost Book");  
            popupTest3.addActionListener(new ActionListener()
            {
				@Override
				public void actionPerformed(ActionEvent arg0) 
				{
					// TODO Auto-generated method stub
					int row = historyTable.table.getSelectedRow();
					int bn = Integer.parseInt(historyTable.table.getValueAt(row, 0).toString());
					if (JOptionPane.showConfirmDialog(WelcomeUI.wui,"Are you sure?", "Quitting",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
					{
						int returnBookResult = luip.librarianReturnBook(null, bn);
						switch (returnBookResult)
						{
						
							case 2: // lost book update successfully
							{
								
								JOptionPane.showMessageDialog( WelcomeUI.wui, "Update Successfully!","Lost Book",JOptionPane.INFORMATION_MESSAGE);
								break;
							} 
							default: // Error
							{
								JOptionPane.showMessageDialog( WelcomeUI.wui, "Operation failed!","Warning",JOptionPane.ERROR_MESSAGE);				
								break;
							}
					  } // switch
					}
 
				}
			});  
//==================================================================================================================			
			//  right click menu on table "manual Extension"

            popup = new JPopupMenu();
            popupTest1=new JMenuItem("Manual Extension");  

            popupTest1.addActionListener(new ActionListener() {
				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					// TODO Auto-generated method stub
					int row = historyTable.table.getSelectedRow();
					int bn = Integer.parseInt(historyTable.table.getValueAt(row, 0).toString());
					String end_date_stringFROM = historyTable.table.getValueAt(row, 5).toString();
					
					//TODO check with Roman if the display of the dates in the table will be changed!!!!
					// Convert to the correct date type to avoid errors
					DateFormat dateFormatFROM = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
					DateFormat dateFormatTO = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
					Date end_dateFROM;
					try 
					{
						end_dateFROM = dateFormatFROM.parse(end_date_stringFROM);
						String end_date_stringTO = dateFormatTO.format(end_dateFROM);
						Date end_dateTO = dateFormatTO.parse(end_date_stringTO);
						String[] dates = new String[OBLSettings.MANUAL_EXT_MAX_DAYS];
						
						// Generate all available dates
						Calendar endCal = Calendar.getInstance();
						endCal.setTime(end_dateTO);
						// Generate all available dates
						for (int i=0; i<OBLSettings.MANUAL_EXT_MAX_DAYS; i++)
						{
							dates[i] = dateFormatTO.format(endCal.getTime());
							endCal.add(Calendar.DATE, 1);							
						}
						
						String new_end_date = null;
						ComboBoxInJOptionPane comboOP = new ComboBoxInJOptionPane();
						//setLocationRelativeTo(LibrarianViewHistory.getCurrentPanel());
						comboOP.setLocationRelativeTo(getParent());
		  				new_end_date = (String) JOptionPane.showInputDialog(WelcomeUI.wui,"Manual Extension",end_date_stringTO, JOptionPane.INFORMATION_MESSAGE, 
		  		    			null, dates,end_date_stringTO);
						comboOP.dispose();
		  		  		if (new_end_date == null)
		  		  		{
		  		  			JOptionPane.showMessageDialog( WelcomeUI.wui, "No date selected!" ,"Manual Extension",JOptionPane.ERROR_MESSAGE);
		  		  		}
		  		  		else
		  		  		{
							System.out.println("Manual Extension for BN="+bn+"  current end date="+end_date_stringTO+ " new end date="+new_end_date);
							int man_ext_res = subUI.getLuip().manualExtension(bn, end_date_stringTO, new_end_date);
							
							switch(man_ext_res)
							{
								case -99:
								{
									JOptionPane.showMessageDialog( WelcomeUI.wui, "Operation Failed!" ,"Manual Extension",JOptionPane.ERROR_MESSAGE);
									break;
								}
								case -4:
								{
									JOptionPane.showMessageDialog( WelcomeUI.wui, "Error! Input date is wrong!" ,"Manual Extension",JOptionPane.ERROR_MESSAGE);
									break;
								}							
								case -3:
								{
									JOptionPane.showMessageDialog( WelcomeUI.wui, "Cannot extend 'wanted' books." ,"Manual Extension",JOptionPane.ERROR_MESSAGE);
									break;
								}
								case -2:
								{
									JOptionPane.showMessageDialog( WelcomeUI.wui, "Error! Cannot extend more than "+OBLSettings.MANUAL_EXT_MAX_DAYS+" days!" ,"Manual Extension",JOptionPane.ERROR_MESSAGE);
									break;
								}
								case -1:
								{
									JOptionPane.showMessageDialog( WelcomeUI.wui, "Input Error!" ,"Manual Extension",JOptionPane.ERROR_MESSAGE);
									break;
								}
								case 1:
								{
									JOptionPane.showMessageDialog( WelcomeUI.wui, "Extended successfully!" ,"Manual Extension",JOptionPane.INFORMATION_MESSAGE);
									// Change the format ... //TODO Change this if roman changes the format..
									//new_end_date = dateFormatFROM.format(end_dateTO);
									//historyTable.table.setValueAt(new_end_date, row, 5);
									break;
								}
							} // end of switch*/
		  		  		}
					} 
					catch (ParseException e) 
					{
						e.printStackTrace();
						JOptionPane.showMessageDialog( WelcomeUI.wui, "Error converting Dates!" ,"Error",JOptionPane.ERROR_MESSAGE);
					}

				}
			});  
              
            popup.add(popupTest1); 
            popup.add(popupTest3); 
            
            
			
		    historyTable.table.addMouseListener(new MouseAdapter() {
		        @Override
		        public void mouseReleased(MouseEvent e) {
		            int r = historyTable.table.rowAtPoint(e.getPoint());
		            if (r >= 0 && r < historyTable.table.getRowCount()) 
		            {
		            	historyTable.table.setRowSelectionInterval(r, r);
		            } else {
		            	historyTable.table.clearSelection();
		            }

		            int rowindex = historyTable.table.getSelectedRow();
		            if (rowindex < 0)
		                return;
		            if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) 
		            {
			        	String borrowed = LibrarianViewHistory.this.man_ext_book_borrowed;
			        	if (borrowed.equals("no"))
			        	{
			        		popup.show(e.getComponent(), e.getX(), e.getY());
			        	}
		            }
	        	}
		    });
		    MyTableCellRenderer myTCR = new MyTableCellRenderer(historyTable);
		    for (int i=0; i < historyTable.table.getColumnCount(); i++)
		    	historyTable.table.getColumnModel().getColumn(i).setCellRenderer(myTCR);
		}//init
//=============================================================================================		
		public int calculateLatnessPiriod(String returnDate , String actualReturnDate) 
		{
			int lateDays = 0 ;

			if(!returnDate.isEmpty()&&!actualReturnDate.isEmpty())
			{	
				try 
				{
					Date ret_date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(returnDate);
					Date acu_ret_date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(actualReturnDate);
					
					if(ret_date.getYear() == acu_ret_date.getYear())	
					{	
						if(ret_date.getMonth() == acu_ret_date.getMonth()) //6.12  = 6.12
						{
							int days = acu_ret_date.getDay() - ret_date.getDay();
							
							if(days >= 0)
								lateDays = days;
						}
						else if(ret_date.getMonth() < acu_ret_date.getMonth()) //10.2.12 < 3.6.12
						{
							int months = (acu_ret_date.getMonth() - ret_date.getMonth()) * 30;
							lateDays = months ;
							int days = acu_ret_date.getDay() - ret_date.getDay();
							if(days >= 0)
							  lateDays = months + days ;
						}
						
					}
					else if(ret_date.getYear() < acu_ret_date.getYear())
					{
						if(ret_date.getMonth() == acu_ret_date.getMonth()) //6.12  =  6.12
						{
							int days = acu_ret_date.getDay() - ret_date.getDay();
							int years = (acu_ret_date.getYear() - ret_date.getYear()) * 365;//years in days
							lateDays = years;
							if(days >= 0)
								lateDays += days;
						}
						else if(ret_date.getMonth() < acu_ret_date.getMonth()) //10.2.12 < 3.6.12
						{
							int years = (acu_ret_date.getYear() - ret_date.getYear()) * 365;//years in days
							int months = (acu_ret_date.getMonth() - ret_date.getMonth()) * 30;//months in days
							lateDays += months + years ; 
							int days = acu_ret_date.getDay() - ret_date.getDay();
							if(days >= 0)
							   lateDays +=  days ;
						}

					 }

				}//try
				catch (ParseException e) 
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

		     }
			return lateDays;
		}
//=============================================================================================	
		public int calculateFine(String bookLost ,int LateDays )
		{
			int fine = 0 ;
			
			if(bookLost.equals("yes"))
			{
				fine = OBLSettings.FineForLoosingBook;
			}
			
			fine = fine + ( LateDays*OBLSettings.FineForLatnnessDay);
			
			return fine ; 
		}
//=============================================================================================	
		public void showHistory(String userID) //calling this function from subscriberUI -> btnViewHistory.addActionListener(new ActionListener() {...
		{
			answer = subUI.subscriberUIP.viewSubscriberHistory(userID);
			int last_row_index;
			historyTable.model.setRowCount(0);
			
			if(answer.getMsg_result() == 0)
				JOptionPane.showMessageDialog( WelcomeUI.wui, "there was an error in retrieving your history " ,"Warning",JOptionPane.WARNING_MESSAGE);
			else if(answer.getBorrowList().isEmpty())
				JOptionPane.showMessageDialog( WelcomeUI.wui, "you dont have any history " ,"Information",JOptionPane.INFORMATION_MESSAGE);
			else
			{	
				historyTable.model.setRowCount(0);
				 last_row_index = historyTable.model.getRowCount() - 1;
				for(BorrowRecored var : answer.getBorrowList())
				{
					historyTable.model.addRow(new Object[] {var.borrowNumber,var.bookISBN,var.copyID,var.bookName,var.borrowDate,var.returnDate,var.actualReturnDate});
					last_row_index = historyTable.model.getRowCount() - 1;
					System.out.println("inserted tow index = "+last_row_index);
					if (var.bookReturned.equals("yes"))
						historyTable.setRowColour(last_row_index,Color.green);
					else
						historyTable.setRowColour(last_row_index,Color.orange);
					if (var.bookLost.equals("yes"))
						historyTable.setRowColour(last_row_index,Color.red);
				}
			 }
		}
	//=============================================================================================		
		public static Component getCurrentPanel()
		{
			return curr_panel;
		}
	//=============================================================================================		
		static class ComboBoxInJOptionPane extends JFrame
		{
			static final String Select = "Select a date";
			String input = "";
			static String[] a = {"Cricket", "FootBall", "Tennis", "Hockey" };
			
			public ComboBoxInJOptionPane() 
			{
				super(Select);
			}
		    public void display()
		    {
				System.out.println("Componenect = "+LibrarianViewHistory.getCurrentPanel());
				//setLocationRelativeTo(LibrarianViewHistory.getCurrentPanel());
				
			  	ActionListener lst = new ActionListener() 
			  	{
			  		public void actionPerformed(ActionEvent e) 
			  		{
			  			input = (String) JOptionPane.showInputDialog(ComboBoxInJOptionPane.this,
			    		"Please select a new return date:",Select, JOptionPane.INFORMATION_MESSAGE, 
			    		null, a,"Tennis");
			  			//JOptionPane.showMessageDialog(null,"You have selected: "+input);
			  		}
			  	};
			  	System.out.println(input);

			  	pack();
			    setVisible(false);
		    }
		}
		
		public void paintComponent(Graphics g) 
		{
			g.drawImage((OBLSettings.IMG_DEFAULT_BACKGROUND).getImage(), 0, 0, OBLSettings.pane2Size[0], OBLSettings.pane2Size[1],null);
			
		}
}//class
